<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    style="min-width: 1400px;"
    :visible.sync="visible">
    <el-form :model="appConf" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="配置标题" prop="name">
        <el-input v-model="appConf.name" placeholder="请输入轮播配置名称（如：春节用）" style="width: 300px;"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="配置描述" prop="remark" v-if="appConf.confType === 'miniAppSelect'">
        <div>
          <el-input v-model="appConf.remark"
                    maxlength="100"
                    placeholder="100字内"
                    type="textarea"
                    :rows="3"></el-input>
        </div>
      </el-form-item>
      <div class="item-wrapper"
           style="display: flex;flex-direction: row;">
        <div class="item-pic-wrapper"
             style="margin-right: 150px;">
          <span style="color: #f56c6c;margin-right: 4px">*</span>配置项banner图：
          <div style="font-size: 12px;margin-right: 6px;">限传一张图片,图片尺寸最佳为600X240像素</div>
          <div class="coverImg-wrapper pic">
            <el-upload ref="uploadCoverImg"
                       :action="uploadCoverImgUrl"
                       :before-upload="beforeCoverImgUpload"
                       :on-error="handleCoverImgError"
                       :on-success="handleCoverImgSuccess"
                       :show-file-list="showCoverImgUpload">
              <img v-if="appConf.bannerImg"
                   class="coverImg"
                   :src="appConf.bannerImg">
              <i v-else
                 class="el-icon-plus coverImg-uploader-icon"></i>
            </el-upload>
            <!--<span style="font-size: 12px;margin-left: 12px;margin-right: 6px;">限传一张图片,图片尺寸最佳为400X480像素</span>-->
          </div>
          <span class="error-tip">{{coverImgErrorTip}}</span>
        </div>
      </div>
      <div style="display: flex;">
        <div style="margin-top: 20px;width: 80px;">
          <span style="color: #f56c6c;margin-right: 4px">*</span>轮播内容
        </div>
        <div>
          <div v-for="(item,index) in itemList" style="margin-top: 10px;" :key="index"
               v-dragging="{ item: item, list: itemList, group: 'item' }">
            <div class="move-tip-icon">&lt;&gt;</div>
            <el-autocomplete
              style="width: 240px;"
              v-model="itemList[index].selectedItem.nameCode"
              clearable
              :hide-loading="true"
              :fetch-suggestions="querySearch"
              placeholder="请输入绘本ID或者绘本名称"
              :trigger-on-focus="false"
              @select="handleSelect"
              @focus="getFocusInput(item,index)">
              <template slot-scope="{ item }">
                <div>{{ item.name }}</div>
              </template>
            </el-autocomplete>
            <el-select v-model="item.selectedSubItem.id" v-if="item.subItems&&item.subItems.length>0">
              <!--<el-select v-model="item.selectedSubItem.id">-->
              <el-option
                v-for="subItem in item.subItems"
                :key="subItem.id"
                :label="subItem.itemName"
                :value="subItem.id">
              </el-option>
            </el-select>
            <el-button type="danger" icon="el-icon-delete" circle @click="deleteItem(index)"
                       :style="{'margin-left':(item.subItems&&item.subItems.length>0)?'0px':'0px'}"></el-button>
          </div>
        </div>
      </div>
      <el-form-item>
        <el-button type="primary" @click="addList" style="margin-top: 20px;">新增一项</el-button>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    <div style="margin-left: 80px;color:#f56c6c;" v-if="showErrorTip">
      <i class="el-icon-warning" style="color: red;margin-right: 10px;"></i>还有信息未填完整，请检查！
    </div>
    <div style="margin-left: 80px;" v-if="appConf.confType != 'hot'">
      <i class="el-icon-warning" style="color: red;margin-right: 10px;"></i>{{attentionTip}}
    </div>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        // 上传图片配置项
        coverImgErrorTip: '',
        showCoverImgUpload: true,
        bannerImgErrorTip: '',
        showBannerImgUpload: true,
        uploadCoverImgUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        uploadBannerImgUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),

        attentionTip: '注意：暂时最多配置50条小程序精选',
        selectedInputItemIndex: 0,
        id: '',
        showErrorTip: false,
        bookConfs: [],
        itemList: [{
          selectedItem: {//选中的绘本
            'id': '',
            'nameCode': '',
          },
          selectedSubItem: {//选中的绘本子项
            'id': '',
            'itemName': '',
          },
          subItems: []//当前绘本的所有子项
        }],
        title: '小程序精选配置',
        appConf: {
          id: '',
          confType: 'miniAppSelect',
          confSecondType: '',
          name: '',
          remark: '',
          bannerImg: ''
        },
        dataRule: {
          name: [
            {required: true, message: '配置名称不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      init (id,popup) {
        let _this = this
        _this.showErrorTip = false
        _this.id = id || 0
        _this.visible = true
        _this.appConf.confType = popup.confType
        _this.appConf.confSecondType = popup.confSecondType
        _this.title = popup.title
        _this.itemList = [{
          selectedItem: {//选中的绘本
            'id': '',
            'nameCode': '',
          },
          selectedSubItem: {//选中的绘本子项
            'id': '',
            'itemName': '',
          },
          subItems: []//当前绘本的所有子项
        }]
        _this.$nextTick(() => {
          _this.$refs['dataForm'].resetFields()
          _this.coverImgErrorTip = ''
          _this.appConf.bannerImg = ''
          if (_this.id) {
            _this.$http({
              url: _this.$http.adornUrl(`/picbook/appconf/info/${_this.id}`),
              method: 'get',
              params: _this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0 && data.data && data.data.bookConfs && data.data.bookConfs.length > 0) {
                _this.appConf = data.data.appConf
                _this.itemList = []
                data.data.bookConfs.forEach(function (item) {
                  _this.itemList.push({
                    selectedItem: {//选中的绘本
                      'id': item.bookId,
                      'nameCode': item.nameCode,
                    },
                    selectedSubItem: {//选中的绘本子项
                      'id': item.bookItemId,
                      'itemName': item.itemName,
                    },
                    subItems: item.itemList//当前绘本的所有子项
                  })
                })
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        let _this = this
        _this.showErrorTip = false
        if (!_this.appConf.bannerImg) {
          _this.coverImgErrorTip = '请上传banner图'
        }
        _this.itemList.map(function (value, index, array) {
          if (!value.selectedItem.id) {
            _this.showErrorTip = true
            return
          }
        })
        _this.$refs['dataForm'].validate((valid) => {
          if (valid && !_this.showErrorTip && _this.appConf.bannerImg) {
            var bookConfs = []
            _this.itemList.map(function (value, index, array) {
              var bookConf = {bookId: value.selectedItem.id}
              if (value.selectedSubItem.id) {
                bookConf.bookItemId = value.selectedSubItem.id
              }
              bookConfs.push(bookConf)
            })
            _this.$http({
              url: _this.$http.adornUrl(`/picbook/appconf/${!_this.id ? 'save' : 'update'}`),
              method: 'post',
              data: _this.$http.adornData({
                appConf: _this.appConf,
                bookConfs: bookConfs
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                _this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 500,
                  onClose: () => {
                    _this.visible = false
                    _this.$emit('refreshDataList')
                  }
                })
              } else {
                _this.$message.error(data.msg)
              }
            })
          }
        })
      },
      addList () {
        if (!this.appConf.confType) {
          return
        }
        var maxCount = 50
        if (this.itemList.length < maxCount) {
          this.itemList.push({
            selectedItem: {//选中的绘本
              'id': '',
              'nameCode': '',
            },
            selectedSubItem: {//选中的绘本子项
              'id': '',
              'itemName': '',
            },
            subItems: []//当前绘本的所有子项
          })
        } else {
          this.$message.warning('最多配置50条小程序精选')
        }
      }      ,
      deleteItem (index) {
        if (this.itemList.length > index && this.itemList.length > 1) {
          this.itemList.splice(index, 1)
        } else if (index == 0 && this.itemList.length == 1) {
          this.itemList = [{
            selectedItem: {//选中的绘本
              'id': '',
              'nameCode': '',
            },
            selectedSubItem: {//选中的绘本子项
              'id': '',
              'itemName': '',
            },
            subItems: []//当前绘本的所有子项
          }]
        }
      }      ,
      getFocusInput (item, index) {
        this.selectedInputItemIndex = index
      }      ,
      querySearch (queryString, cb) {
        this.$http({
          url: this.$http.adornUrl('/picbook/combobox/listSimpleBook'),
          method: 'post',
          data: this.$http.adornData({
            'text': queryString
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            cb(data.data)
          } else {
            cb([])
          }
        }).catch(() => {
          cb([])
        })

      },
      handleSelect (item) {
        var _this = this
        _this.itemList[_this.selectedInputItemIndex].selectedItem = item
        //查询绘本子项
        _this.$http({
          url: _this.$http.adornUrl(`/picbook/combobox/listSimpleItem/` + item.id),
          method: 'post',
          data: _this.$http.adornData({
            'bookId': item.id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            _this.itemList[_this.selectedInputItemIndex].subItems = data.data
          }
        })
      },
      handleCoverImgSuccess (res, file) {
        this.appConf.bannerImg = res.url
        let _this = this
        setTimeout(function () {
          _this.$refs.uploadCoverImg.clearFiles()
        }, 1000)
      },
      beforeCoverImgUpload (file) {
        this.coverImgErrorTip = ''
        if (file.type.indexOf('image') < 0) {
          this.coverImgErrorTip = '图片格式不正确'
          return false
        }
      },
      handleCoverImgError (err, file, fileList) {
        this.coverImgErrorTip = '上传失败'
      },
      handleBannerImgSuccess (res, file) {
        this.appConf.bannerImg = res.url
        let _this = this
        setTimeout(function () {
          _this.$refs.uploadBannerImg.clearFiles()
        }, 1000)
      },
      beforeBannerImgUpload (file) {
        this.bannerImgErrorTip = ''
        if (file.type.indexOf('image') < 0) {
          this.bannerImgErrorTip = '图片格式不正确'
          return false
        }
      },
      handleBannerImgError (err, file, fileList) {
        this.bannerImgErrorTip = '上传失败'
      },
      previewPicBook () {
        let _this = this
        _this.$emit('previewPicBook', _this.appConf)
      },
      uploadProgress (p) {
        this.progress = Math.floor(p * 100)
      },
    }
  }
</script>
<style lang="less" scoped>
  .move-tip-icon {
    display: inline-block;
    font-size: 18px;
    font-weight: 400;
    transform: rotate(90deg);
    -ms-transform: rotate(90deg); /* IE 9 */
    -moz-transform: rotate(90deg); /* Firefox */
    -webkit-transform: rotate(90deg); /* Safari 和 Chrome */
    -o-transform: rotate(90deg); /* Opera */
  }

  .item-wrapper {
    border: 1px solid #ddd;
    padding: 12px;
    border-radius: 4px;
    margin-bottom: 12px;
    width: 100%;
    .price-item-wrapper {
      display: flex;
      flex-direction: row;
      align-items: center;
      .el-form-item__content {
        float: left;
      }
      .price-input {
        width: 120px;
        margin-left: 10px;
        height: 36px;
        line-height: 36px;
        border-radius: 4px;
        -webkit-appearance: none;
        border: 1px solid #dcdfe6;
        color: #606266;
        padding: 0 15px;
      }
    }
    .item-pic-wrapper {
      display: inline-block;
      .pic {
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-right: 20px;
      }
      .avatar-uploader .el-upload {
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }

      .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
      }
      .coverImg-wrapper {
        .coverImg-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          border: 1px solid #d9d9d9;
          border-radius: 6px;
          width: 125px;
          height: 150px;
          line-height: 150px;
          text-align: center;
        }
        .coverImg {
          width: 125px;
          height: 150px;
          display: block;
        }
      }
      .bannerImg-wrapper {
        .bannerImg-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          border: 1px solid #d9d9d9;
          border-radius: 6px;
          width: 266px;
          height: 150px;
          line-height: 150px;
          text-align: center;
        }
        .bannerImg {
          width: 266px;
          height: 150px;
          display: block;
        }
      }
    }
  }
  .el-form-item {
    margin-bottom: 18px;
  }

  .no-bottom-maring.el-form-item {
    margin-bottom: 0px;
  }

  .error-tip {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
  }

  /** 去除input输入框样式 */
  input[type=number]::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
</style>
